import 'package:bilibili/http/core/sun_error.dart';
import 'package:bilibili/http/core/sun_net_adapter.dart';
import 'package:bilibili/http/request/base_request.dart';
import 'package:dio/dio.dart';

class DioAdapter extends SunNetAdapter {
  @override
  Future<SunNetResponse<T>> send<T>(BaseRequest request) async {
    Response? response;
    var option = Options(headers: request.header);
    var error;
    try {
      var method = request.httpMethod();
      switch (method) {
        case HttpMethod.GET:
          response = await Dio().get(request.url(), options: option);
          break;
        case HttpMethod.POST:
          response = await Dio()
              .post(request.url(), data: request.params, options: option);
          break;
        case HttpMethod.DELETE:
          response = await Dio()
              .delete(request.url(), data: request.params, options: option);
          break;
        case HttpMethod.PUT:
          response = await Dio()
              .put(request.url(), data: request.params, options: option);
          break;
      }
    } on DioError catch (e) {
      error = e;
      response = e.response;
    } catch (e) {
      error = e;
    }
    if (error != null) {
      throw SunNetError(response?.statusCode ?? -1, error.toString(),
          data: buildRes(response, request));
    }
    return buildRes(response, request);
  }

  SunNetResponse<T> buildRes<T>(Response? response, BaseRequest request) {
    return SunNetResponse<T>(
        data: response?.data,
        request: request,
        statusCode: response?.statusCode ?? -1,
        statusMessage: response?.statusMessage,
        extra: response);
  }
}
